{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "29dd7e577fbf8a15",
   "metadata": {},
   "source": [
    "### 1. 变量与数据类型\r\n",
    "\r\n",
    "#### 讲解：\r\n",
    "\r\n",
    "在Python中，变量是用来存储数据的容器，它们不需要事先声明类型，也不需要手动分配内存。Python会根据你赋给变量的值来自动推断变量的类型。数据类型决定了变量可以存储什么样的数据以及可以对这些数据进行哪些操作。\r\n",
    "\r\n",
    "常见的数据类型包括：\r\n",
    "\r\n",
    "- **整数（int）**：用于表示没有小数部分的数字。例如：`5`, `-3`, `42`\r\n",
    "- **浮点数（float）**：用于表示带有小数部分的数字。例如：`3.14`, `-0.001`, `2.0`\r\n",
    "- **字符串（str）**：用于表示文本数据。字符串可以用单引号`'`或双引号`\"`括起来。例如：`\"Hello, World!\"`, `'Python编程'`\r\n",
    "- **布尔值（bool）**：用于表示逻辑值，只有两个取值：`True`（真）或`False`（假）。布尔值通常用于条件判断。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "372b6dd7bfa02c18",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T16:59:53.009595Z",
     "start_time": "2024-09-01T16:59:53.005848Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "复数: (3+4j)\n",
      "年龄的数据类型: <class 'int'>\n",
      "价格的数据类型: <class 'float'>\n",
      "姓名的数据类型: <class 'str'>\n",
      "是否为学生的数据类型: <class 'bool'>\n",
      "复数的数据类型: <class 'complex'>\n"
     ]
    }
   ],
   "source": [
    "# 常见数据类型\n",
    "age = 25  # 整数\n",
    "price = 19.99  # 浮点数\n",
    "name = \"Alice\"  # 字符串\n",
    "is_student = True  # 布尔值\n",
    "\n",
    "# 复数\n",
    "complex_num = 3 + 4j\n",
    "print(\"复数:\", complex_num)\n",
    "\n",
    "# 查看数据类型\n",
    "print(\"年龄的数据类型:\", type(age))\n",
    "print(\"价格的数据类型:\", type(price))\n",
    "print(\"姓名的数据类型:\", type(name))\n",
    "print(\"是否为学生的数据类型:\", type(is_student))\n",
    "print(\"复数的数据类型:\", type(complex_num))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcfd2cbec1306156",
   "metadata": {},
   "source": [
    "### 2. 基本操作符\r\n",
    "\r\n",
    "#### 讲解：\r\n",
    "\r\n",
    "在Python中，操作符用于执行变量和数值之间的操作。常见的操作符包括：\r\n",
    "\r\n",
    "- **算术操作符**：用于执行基本的数学运算，如加法、减法、乘法、除法等。\r\n",
    "- **比较操作符**：用于比较两个值，并返回一个布尔值（True或False）。\r\n",
    "- **逻辑操作符**：用于在条件表达式中进行逻辑运算，如与（and）、或（or）、非（not）等。\r\n",
    "\r\n",
    "掌握这些操作符可以帮助我们在编程中进行数学计算、判断条件，以及控制程序的执行流程。\r\n",
    "\r\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2edf8014f84f5766",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:01:20.438049Z",
     "start_time": "2024-09-01T17:01:20.432114Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "加法: 13\n",
      "减法: 7\n",
      "乘法: 30\n",
      "除法: 3.3333333333333335\n",
      "取余: 1\n",
      "幂: 1000\n",
      "a等于b: False\n",
      "a不等于b: True\n",
      "a大于b: True\n",
      "a小于等于b: False\n",
      "a大于5且b小于5: True\n",
      "a小于5或b大于5: False\n",
      "非a等于b: True\n"
     ]
    }
   ],
   "source": [
    "# 算术操作符\n",
    "a = 10\n",
    "b = 3\n",
    "print(\"加法:\", a + b)     # 10 + 3 = 13\n",
    "print(\"减法:\", a - b)     # 10 - 3 = 7\n",
    "print(\"乘法:\", a * b)     # 10 * 3 = 30\n",
    "print(\"除法:\", a / b)     # 10 / 3 = 3.333...\n",
    "print(\"取余:\", a % b)     # 10 % 3 = 1 (求模运算，返回除法的余数)\n",
    "print(\"幂:\", a ** b)      # 10 ** 3 = 1000 (10的3次方)\n",
    "\n",
    "# 比较操作符\n",
    "print(\"a等于b:\", a == b)   # False (10不等于3)\n",
    "print(\"a不等于b:\", a != b)  # True (10确实不等于3)\n",
    "print(\"a大于b:\", a > b)     # True (10大于3)\n",
    "print(\"a小于等于b:\", a <= b) # False (10不小于或等于3)\n",
    "\n",
    "# 逻辑操作符\n",
    "print(\"a大于5且b小于5:\", a > 5 and b < 5) # True (两个条件都为真)\n",
    "print(\"a小于5或b大于5:\", a < 5 or b > 5)  # False (两个条件都为假)\n",
    "print(\"非a等于b:\", not(a == b))         # True (取反，a == b为False，取反后为True)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63834f59b66d3edb",
   "metadata": {},
   "source": [
    "### 3. 条件语句\r\n",
    "\r\n",
    "#### 讲解：\r\n",
    "\r\n",
    "条件语句是编程中用于控制代码执行流程的基本工具。通过条件语句，程序可以根据特定条件的真假来决定执行哪一段代码，从而实现更加灵活和智能的行为。\r\n",
    "\r\n",
    "Python中的条件语句包括以下几种：\r\n",
    "\r\n",
    "- **if** 语句：用于判断条件是否为真，如果为真，则执行对应的代码块。\r\n",
    "- **elif** 语句（else if的缩写）：用于检查其他条件，当前面的条件不满足时，可以使用`elif`来检查另一个条件。\r\n",
    "- **else** 语句：用于在前面的所有条件都不满足的情况下，执行一个默认的代码块。\r\n",
    "\r\n",
    "通过组合这些语句，程序可以实现复杂的分支逻辑。此外，条件语句中还可以结合逻辑操作符（如`and`、`or`、`not`）来处理多重条件判断。\r\n",
    "\r\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e667c841387f3e22",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "良好\n",
      "成年人\n"
     ]
    }
   ],
   "source": [
    "# 条件语句示例\n",
    "score = 85\n",
    "\n",
    "if score >= 90:\n",
    "    print(\"优秀\")\n",
    "elif score >= 75:\n",
    "    print(\"良好\")\n",
    "else:\n",
    "    print(\"及格\")\n",
    "\n",
    "# 结合逻辑操作符的条件语句\n",
    "age = 20\n",
    "if age >= 18 and age < 60:\n",
    "    print(\"成年人\")\n",
    "else:\n",
    "    print(\"未成年人或老年人\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc7b442af93872c2",
   "metadata": {},
   "source": [
    "### 4. 循环结构\r\n",
    "\r\n",
    "#### 讲解：\r\n",
    "\r\n",
    "循环结构用于在满足特定条件的情况下重复执行某段代码，直到条件不再满足。Python中最常用的两种循环结构是`for`循环和`while`循环。\r\n",
    "\r\n",
    "- **for循环**：通常用于遍历序列（如列表、元组、字符串等）或执行一个确定次数的循环。`for`循环会依次取出序列中的每一个元素，直到序列遍历完毕。\r\n",
    "- **while循环**：根据一个条件表达式来决定是否继续执行循环，只要条件为真，循环就会持续执行。通常用于当循环的次数未知但有明确的退出条件时。\r\n",
    "\r\n",
    "此外，Python还提供了`break`和`continue`语句，进一步控制循环的执行：\r\n",
    "\r\n",
    "- **break**：用于立即退出当前循环，无论条件是否已经满足，循环都将终止。\r\n",
    "- **continue**：用于跳过当前循环的剩余代码，直接进入下一次循环的迭代。\r\n",
    "\r\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "51fac9509f3eb557",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:07:14.562741Z",
     "start_time": "2024-09-01T17:07:14.558300Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "循环次数: 0\n",
      "循环次数: 1\n",
      "循环次数: 2\n",
      "循环次数: 3\n",
      "循环次数: 4\n",
      "计数: 0\n",
      "计数: 1\n",
      "计数: 2\n",
      "计数: 3\n",
      "计数: 4\n",
      "当前值: 1\n",
      "当前值: 3\n",
      "当前值: 5\n",
      "当前值: 7\n"
     ]
    }
   ],
   "source": [
    "# for循环示例\n",
    "for i in range(5):\n",
    "    print(\"循环次数:\", i)\n",
    "\n",
    "# while循环示例\n",
    "count = 0\n",
    "while count < 5:\n",
    "    print(\"计数:\", count)\n",
    "    count += 1\n",
    "\n",
    "# 使用continue和break的循环示例\n",
    "for i in range(10):\n",
    "    if i % 2 == 0:\n",
    "        continue  # 跳过所有偶数\n",
    "    if i > 7:\n",
    "        break  # 当i大于7时退出循环\n",
    "    print(\"当前值:\", i)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd6b3121fc932514",
   "metadata": {},
   "source": [
    "### 5. 函数与模块导入\r\n",
    "\r\n",
    "#### 讲解：\r\n",
    "\r\n",
    "**函数**是编程中用于封装特定功能或任务的代码块。使用函数可以使代码更加简洁、可重用和易于维护。Python内置了许多常用函数，如`print()`、`len()`等，它们可以直接使用。此外，Python允许我们定义自己的函数，以满足特定的需求。\r\n",
    "\r\n",
    "定义函数时，使用`def`关键字，后跟函数名、参数列表（可选）和冒号，然后是缩进的函数体。函数可以有**参数**，用于传递数据，还可以有**返回值**，用于返回计算结果。通过这种方式，函数可以处理输入数据并返回输出结果。\r\n",
    "\r\n",
    "Python的强大之处还在于其丰富的模块库。**模块**是包含一组相关功能的代码文件，导入模块可以让我们轻松使用这些功能，而不必从头编写代码。Python的标准库提供了大量实用模块，如`math`、`os`、`datetime`等。此外，还有第三方库，如`NumPy`、`Pandas`，用于科学计算和数据处理。\r\n",
    "\r\n",
    "模块的导入可以是全量导入，也可以导入模块中的特定部分。我们还可以使用**别名**来简化模块的调用，这在处理名称冲突或为了代码简洁时非常有用。\r\n",
    "\r\n",
    "#### 代码示例：\r\n",
    "\r\n",
    "**定义和使用函数：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7e908e89b448ecfe",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:09:02.517301Z",
     "start_time": "2024-09-01T17:09:02.511670Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Alice\n",
      "3的平方: 9\n",
      "2的三次方: 8\n"
     ]
    }
   ],
   "source": [
    "# 定义一个简单的函数\n",
    "def greet(name):\n",
    "    \"\"\"返回一个问候语句\"\"\"\n",
    "    return \"Hello, \" + name\n",
    "\n",
    "# 使用函数\n",
    "message = greet(\"Alice\")\n",
    "print(message)  # 输出: Hello, Alice\n",
    "\n",
    "# 带有默认参数的函数\n",
    "def power(base, exponent=2):\n",
    "    \"\"\"返回base的exponent次幂\"\"\"\n",
    "    return base ** exponent\n",
    "\n",
    "print(\"3的平方:\", power(3))          # 输出: 3的平方: 9\n",
    "print(\"2的三次方:\", power(2, 3))      # 输出: 2的三次方: 8\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3305e9336d942f4",
   "metadata": {},
   "source": [
    "**代码讲解：**\r\n",
    "\r\n",
    "- `greet(name)` 是一个简单的函数，它接收一个参数`name`，并返回一个问候语句。\r\n",
    "- `power(base, exponent=2)` 是一个带有默认参数的函数。如果不提供`exponent`参数，函数会默认计算平方。可以通过指定不同的`exponent`来计算不同的幂。\r\n",
    "\r\n",
    "这些示例展示了如何定义和调用函数，以及如何使用默认参数来增强函数的灵活性。\r\n",
    "\r\n",
    "**模块导入和使用：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5cf5bf9a88a2bef",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:10:08.204549Z",
     "start_time": "2024-09-01T17:10:08.050624Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "16的平方根: 4.0\n",
      "当前工作目录: C:\\Users\\Administrator\\Desktop\\财经学院课程\n"
     ]
    }
   ],
   "source": [
    "# 模块导入\n",
    "import math  # 导入数学模块\n",
    "\n",
    "# 使用模块中的函数\n",
    "result = math.sqrt(16)\n",
    "print(\"16的平方根:\", result)  # 输出: 16的平方根: 4.0\n",
    "\n",
    "import os  # 导入操作系统模块\n",
    "\n",
    "# 使用os模块中的函数\n",
    "current_directory = os.getcwd()\n",
    "print(\"当前工作目录:\", current_directory)  # 输出当前工作目录\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e768d910-48fe-4c6c-a5ea-897c232b235c",
   "metadata": {},
   "source": [
    "**代码讲解：**\n",
    "\n",
    "- `import math` 导入了Python的数学模块，`math.sqrt(16)` 调用该模块的平方根函数来计算16的平方根。\n",
    "- `import os` 导入了操作系统模块，`os.getcwd()` 获取并返回当前工作目录的路径。\n",
    "\n",
    "**导入模块的特定部分：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "077e4779-3b14-46ba-926a-bb8c17f18866",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "圆周率: 3.141592653589793\n",
      "25的平方根: 5.0\n"
     ]
    }
   ],
   "source": [
    "# 导入模块中的特定函数\n",
    "from math import sqrt, pi\n",
    "\n",
    "# 直接使用导入的函数和变量\n",
    "print(\"圆周率:\", pi)               # 输出: 圆周率: 3.141592653589793\n",
    "print(\"25的平方根:\", sqrt(25))      # 输出: 25的平方根: 5.0\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbb8f969-9733-4613-9baf-01760b056850",
   "metadata": {},
   "source": [
    "**代码讲解：**\n",
    "\n",
    "- `from math import sqrt, pi` 只从`math`模块中导入了`sqrt`函数和`pi`常量。这种方式可以减少命名空间中的名称冲突，并提高代码的可读性。\n",
    "\n",
    "**使用别名导入模块：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "65950feb-94f2-4608-8643-4749aa5ef57f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NumPy数组: [1 2 3 4]\n"
     ]
    }
   ],
   "source": [
    "# 使用别名导入模块\n",
    "import numpy as np\n",
    "\n",
    "# 使用别名调用模块中的函数\n",
    "array = np.array([1, 2, 3, 4])\n",
    "print(\"NumPy数组:\", array)  # 输出: NumPy数组: [1 2 3 4]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52bebc96-80a1-4a6a-9178-8b164ecfbf5e",
   "metadata": {},
   "source": [
    "**代码讲解：**\n",
    "\n",
    "- `import numpy as np` 使用别名`np`来引用`numpy`模块。这种方式缩短了模块名称的长度，方便在代码中多次调用。\n",
    "\n",
    "通过这些代码示例和讲解，你可以看到函数的定义和调用是如何使代码更加模块化和高效的。模块导入则让我们能够利用Python生态系统中的强大功能，从而更加专注于解决具体问题。\n",
    "\n",
    "#### 总结：\n",
    "\n",
    "函数和模块导入是Python编程中的重要组成部分。函数帮助我们封装逻辑并提高代码的重用性，而模块导入则让我们能够轻松访问广泛的功能库。掌握这两者的使用，将大大提高你的编程效率和代码质量。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e8fe6d5-b79b-40ed-a2d6-bd845d888277",
   "metadata": {},
   "source": [
    "### 6. 类与对象\n",
    "\n",
    "#### 讲解：\n",
    "\n",
    "**类**是面向对象编程（OOP）的核心概念。它提供了一种在程序中创建新类型的方法。类定义了对象的**属性**和**行为**（通过方法）。**对象**是类的实例，是根据类创建的具体实体。理解类和对象的概念对于编写大型、复杂且易于维护的程序至关重要。\n",
    "\n",
    "在Python中，类通过关键字`class`定义，类的属性在构造函数`__init__()`中初始化，而类中的方法则定义了对象的行为。面向对象编程的优势在于它能够将数据与处理数据的方法封装在一起，从而提高代码的模块化、重用性和扩展性。\n",
    "\n",
    "#### 面向对象编程的基本概念：\n",
    "\n",
    "1. **类（Class）**：是对象的蓝图或模板，定义了对象的属性（变量）和方法（函数）。\n",
    "2. **对象（Object）**：是类的实例，是根据类创建的具体实体。\n",
    "3. **属性（Attributes）**：是类中定义的变量，表示对象的状态或数据。\n",
    "4. **方法（Methods）**：是类中定义的函数，表示对象的行为。\n",
    "5. **封装（Encapsulation）**：是将数据和操作数据的方法封装在一个类中，隐藏对象的内部实现细节。\n",
    "6. **继承（Inheritance）**：允许一个类继承另一个类的属性和方法，从而实现代码的重用。\n",
    "7. **多态（Polymorphism）**：允许不同的对象以相同的方式调用同一个方法，但实际的执行效果可以根据对象的类型有所不同。\n",
    "\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "fa5343b4-dd96-41ea-8213-7e899c03e83b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "狗的名字: Buddy\n",
      "狗的年龄: 3\n",
      "Buddy 说: 汪汪!\n",
      "修改后的狗的年龄: 4\n",
      "狗的品种: Unknown\n",
      "修改后的狗的品种: Golden Retriever\n"
     ]
    }
   ],
   "source": [
    "# 定义一个简单的类\n",
    "class Dog:\n",
    "    \"\"\"一个表示狗的类\"\"\"\n",
    "    \n",
    "    def __init__(self, name, age):\n",
    "        \"\"\"初始化属性name和age\"\"\"\n",
    "        self.name = name  # 公共属性\n",
    "        self.age = age    # 公共属性\n",
    "        self.__breed = \"Unknown\"  # 私有属性\n",
    "    \n",
    "    def bark(self):\n",
    "        \"\"\"模拟狗叫的行为\"\"\"\n",
    "        return self.name + \" 说: 汪汪!\"\n",
    "    \n",
    "    def get_breed(self):\n",
    "        \"\"\"获取狗的品种\"\"\"\n",
    "        return self.__breed\n",
    "    \n",
    "    def set_breed(self, breed):\n",
    "        \"\"\"设置狗的品种\"\"\"\n",
    "        self.__breed = breed\n",
    "\n",
    "# 创建类的实例\n",
    "my_dog = Dog(\"Buddy\", 3)\n",
    "\n",
    "# 访问公共属性\n",
    "print(\"狗的名字:\", my_dog.name)\n",
    "print(\"狗的年龄:\", my_dog.age)\n",
    "\n",
    "# 调用方法\n",
    "print(my_dog.bark())\n",
    "\n",
    "# 修改公共属性\n",
    "my_dog.age = 4\n",
    "print(\"修改后的狗的年龄:\", my_dog.age)\n",
    "\n",
    "# 访问和修改私有属性\n",
    "print(\"狗的品种:\", my_dog.get_breed())  # 通过方法访问私有属性\n",
    "my_dog.set_breed(\"Golden Retriever\")     # 通过方法修改私有属性\n",
    "print(\"修改后的狗的品种:\", my_dog.get_breed())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24c5cf3f-650f-46cc-9b14-401cb2ac53b0",
   "metadata": {},
   "source": [
    "**代码讲解：**\n",
    "\n",
    "1. **类的定义**：\n",
    "   - `class Dog:` 定义了一个名为`Dog`的类。\n",
    "   - `__init__(self, name, age)` 是类的构造函数，用于初始化对象的属性。`self`参数代表类的实例本身，`name`和`age`是传递给构造函数的参数，用来初始化对象的属性。\n",
    "\n",
    "2. **公共属性**：\n",
    "   - `self.name = name` 和 `self.age = age` 是公共属性，表示狗的名字和年龄。公共属性可以在类外部直接访问和修改。\n",
    "\n",
    "3. **私有属性**：\n",
    "   - `self.__breed = \"Unknown\"` 是一个私有属性，表示狗的品种。通过在属性名前加上双下划线`__`，我们将`__breed`属性设置为私有属性。私有属性不能直接在类外部访问或修改。\n",
    "\n",
    "4. **方法的定义**：\n",
    "   - `bark(self)` 是类中的方法，用于模拟狗叫的行为。\n",
    "   - `get_breed(self)` 和 `set_breed(self, breed)` 是用于访问和修改私有属性`__breed`的方法。通过这些方法，类的使用者可以间接访问和修改私有属性。\n",
    "\n",
    "5. **创建对象**：\n",
    "   - `my_dog = Dog(\"Buddy\", 3)` 创建了一个`Dog`类的实例`my_dog`，并初始化它的`name`属性为`Buddy`，`age`属性为3。\n",
    "\n",
    "6. **访问公共属性和调用方法**：\n",
    "   - `my_dog.name` 和 `my_dog.age` 用于访问对象的公共属性。\n",
    "   - `my_dog.bark()` 调用对象的方法，执行定义的行为。\n",
    "\n",
    "7. **修改公共属性**：\n",
    "   - `my_dog.age = 4` 修改了对象的`age`属性，将其从3更改为4。\n",
    "\n",
    "8. **访问和修改私有属性**：\n",
    "   - `my_dog.get_breed()` 通过方法访问私有属性`__breed`。\n",
    "   - `my_dog.set_breed(\"Golden Retriever\")` 通过方法修改私有属性`__breed`。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b91afbfc-a1bb-4aaa-a792-3ab0bb65ba4e",
   "metadata": {},
   "source": [
    "通过这个示例，我们可以看到如何定义一个类并使用它来创建对象，如何访问和修改对象的公共属性，调用对象的方法，以及如何通过方法来访问和修改私有属性。这展示了面向对象编程的基本原则，即将数据和行为封装在一个单一的类中，同时保护数据的隐私性，提高代码的安全性。\n",
    "\n",
    "#### 继承与多态：\n",
    "\n",
    "在面向对象编程中，**继承**允许我们定义一个新类，该类继承自现有的类，继承的类称为子类，现有的类称为父类。子类会自动继承父类的属性和方法，但它也可以重写或扩展这些方法。\n",
    "\n",
    "**多态**则允许子类在继承父类的同时，定义自己独特的行为，即使它们使用相同的方法名。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "7f5d8d19-67b4-449f-83f8-82cc6b8b9e56",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Whiskers 说: 喵喵!\n"
     ]
    }
   ],
   "source": [
    "# 定义一个父类\n",
    "class Animal:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "    \n",
    "    def speak(self):\n",
    "        return self.name + \" 叫了一声。\"\n",
    "\n",
    "# 定义一个子类\n",
    "class Cat(Animal):\n",
    "    def speak(self):\n",
    "        return self.name + \" 说: 喵喵!\"\n",
    "\n",
    "# 使用继承和多态\n",
    "my_cat = Cat(\"Whiskers\")\n",
    "print(my_cat.speak())  # 输出: Whiskers 说: 喵喵!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "794587f5-4684-4f9b-ab26-445ee155f4f7",
   "metadata": {},
   "source": [
    "**代码讲解**：\n",
    "\n",
    "- `Animal` 是一个父类，定义了一个通用的`Animal`类，其中有一个属性`name`和一个方法`speak()`。\n",
    "- `Cat` 是一个子类，继承了`Animal`类。虽然它继承了`speak()`方法，但它重写了该方法，使其输出与`Animal`类不同的行为。\n",
    "- `my_cat.speak()` 调用的是`Cat`类中的`speak()`方法，而不是`Animal`类中的`speak()`方法，这就是多态的体现。\n",
    "\n",
    "通过这些扩展的示例和讲解，你可以更好地理解面向对象编程的核心概念，包括类和对象的定义与使用，以及继承和多态的应用。面向对象编程不仅让代码更具结构性，还可以使代码更容易维护和扩展。\n",
    "\n",
    "---\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9ec1cfa0ac1f672",
   "metadata": {},
   "source": [
    "### 7. 异常处理\r\n",
    "\r\n",
    "#### 讲解：\r\n",
    "\r\n",
    "**异常处理**是编程中用于应对程序运行时可能发生的错误或异常情况的机制。通过异常处理，程序可以在遇到错误时捕获并处理异常，而不是直接崩溃。Python通过`try-except`块进行异常处理，允许我们指定要捕获的异常类型，并定义在异常发生时应执行的代码。\r\n",
    "\r\n",
    "常见的异常类型包括：\r\n",
    "\r\n",
    "- **ZeroDivisionError**：当尝试除以零时抛出的异常。\r\n",
    "- **ValueError**：当传递给函数或操作的数据类型不符合预期时抛出的异常。\r\n",
    "\r\n",
    "此外，Python还提供了一个`finally`块，用于定义无论是否发生异常都要执行的代码。这通常用于清理资源或确保某些操作一定会执行。\r\n",
    "\r\n",
    "Python还允许我们定义**自定义异常**，从而在特定情况下抛出我们自己的异常。这对于处理应用程序中特定的业务逻辑错误非常有用。\r\n",
    "\r\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "2356593556f877c7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:14:47.266625Z",
     "start_time": "2024-09-01T17:14:42.401727Z"
    }
   },
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "输入一个整数:  3\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "结果: 3.3333333333333335\n",
      "结束异常处理\n",
      "数字不能为负数！\n"
     ]
    }
   ],
   "source": [
    "# 异常处理示例\n",
    "try:\n",
    "    number = int(input(\"输入一个整数: \"))\n",
    "    result = 10 / number\n",
    "    print(\"结果:\", result)\n",
    "except ZeroDivisionError:\n",
    "    print(\"错误: 除数不能为零！\")\n",
    "except ValueError:\n",
    "    print(\"错误: 请输入有效的整数！\")\n",
    "finally:\n",
    "    print(\"结束异常处理\")\n",
    "\n",
    "# 自定义异常\n",
    "class NegativeNumberError(Exception):\n",
    "    \"\"\"自定义异常类\"\"\"\n",
    "    pass\n",
    "\n",
    "def check_positive(number):\n",
    "    \"\"\"检查数字是否为正数\"\"\"\n",
    "    if number < 0:\n",
    "        raise NegativeNumberError(\"数字不能为负数！\")\n",
    "    return number\n",
    "\n",
    "try:\n",
    "    check_positive(-5)\n",
    "except NegativeNumberError as e:\n",
    "    print(e)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efc3cfab-f243-4d46-bba9-0402e5571d4a",
   "metadata": {},
   "source": [
    "**代码讲解：**\n",
    "\n",
    "1. **try-except块**：\n",
    "   - `try`块中的代码是可能会引发异常的代码。程序首先尝试执行`try`块中的代码，如果发生异常，则跳到相应的`except`块进行处理。\n",
    "   - `except ZeroDivisionError:` 用于捕获除以零的错误。如果用户输入的数字是0，程序将捕获这个异常并输出“错误: 除数不能为零！”。\n",
    "   - `except ValueError:` 用于捕获无效的整数输入错误。如果用户输入的不是整数（例如字符串），程序将捕获这个异常并输出“错误: 请输入有效的整数！”。\n",
    "   - `finally:` 块中的代码无论是否发生异常都会执行。这通常用于释放资源或执行清理操作，如关闭文件或网络连接。\n",
    "\n",
    "2. **自定义异常**：\n",
    "   - `class NegativeNumberError(Exception):` 定义了一个自定义异常类，用于处理负数输入的错误情况。自定义异常类通常继承自`Exception`类。\n",
    "   - `raise NegativeNumberError(\"数字不能为负数！\")` 在`check_positive`函数中，当检测到输入的数字为负数时，程序会主动抛出`NegativeNumberError`异常。\n",
    "   - `except NegativeNumberError as e:` 捕获自定义的`NegativeNumberError`异常，并输出相应的错误信息。\n",
    "\n",
    "通过使用自定义异常，我们可以针对特定的业务逻辑或错误情况提供更精确的异常处理。这对于构建健壮的应用程序非常重要，特别是在处理用户输入、文件操作或网络请求等可能出现错误的情境时。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b9cf93e-6746-464d-b599-db702ebc4d0f",
   "metadata": {},
   "source": [
    "在这个示例中，程序首先尝试进行整数输入并计算除法操作，如果输入无效或发生除零错误，程序会捕获相应的异常并输出错误信息。无论是否发生异常，程序都会执行`finally`块中的代码，确保完成必要的清理操作。最后，示例还展示了如何通过自定义异常来处理特定的业务逻辑错误，如检测负数输入。\n",
    "\n",
    "通过这些扩展的示例和讲解，你可以深入理解如何使用Python的异常处理机制来构建健壮和可靠的程序。异常处理不仅可以防止程序在遇到错误时崩溃，还可以帮助程序优雅地处理错误，并提供有意义的错误信息给用户或开发者。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "301a67f6-ce7f-4873-98b9-1488ad40282d",
   "metadata": {},
   "source": [
    "`raise` 关键字在 Python 中用于显式地抛出一个异常。你可以在程序的任何位置使用 `raise` 来引发一个指定的异常。通常用于以下几种情况：\n",
    "\n",
    "1. **引发内置异常**：\n",
    "   - 当程序检测到某种错误情况时，可以使用 `raise` 来手动引发一个内置异常，如 `ValueError`、`TypeError`、`ZeroDivisionError` 等。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "1054740f-de10-4590-80bf-6d8471243891",
   "metadata": {},
   "outputs": [
    {
     "ename": "ZeroDivisionError",
     "evalue": "除数不能为零！",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mZeroDivisionError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[21], line 5\u001b[0m\n\u001b[0;32m      3\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mZeroDivisionError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m除数不能为零！\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m      4\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m x \u001b[38;5;241m/\u001b[39m y\n\u001b[1;32m----> 5\u001b[0m divide(\u001b[38;5;241m3\u001b[39m,\u001b[38;5;241m0\u001b[39m)\n",
      "Cell \u001b[1;32mIn[21], line 3\u001b[0m, in \u001b[0;36mdivide\u001b[1;34m(x, y)\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mdivide\u001b[39m(x, y):\n\u001b[0;32m      2\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m y \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[1;32m----> 3\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mZeroDivisionError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m除数不能为零！\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m      4\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m x \u001b[38;5;241m/\u001b[39m y\n",
      "\u001b[1;31mZeroDivisionError\u001b[0m: 除数不能为零！"
     ]
    }
   ],
   "source": [
    "def divide(x, y):\n",
    "    if y == 0:\n",
    "        raise ZeroDivisionError(\"除数不能为零！\")\n",
    "    return x / y\n",
    "divide(3,0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecba75fe-8540-41f1-a194-fb8552d77cb2",
   "metadata": {},
   "source": [
    "1. 在这个示例中，如果 `y` 为 0，则会引发 `ZeroDivisionError` 异常，并显示自定义的错误信息。\r\n",
    "\r\n",
    "2. **引发自定义异常**：\r\n",
    "   - 你可以定义自己的异常类，并在特定情况下使用 `raise` 引发这个异常。这通常用于业务逻辑中特定的错误处理。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "264513ea-f06d-492e-b57c-d9119b949a10",
   "metadata": {},
   "outputs": [],
   "source": [
    "class NegativeNumberError(Exception):\n",
    "    \"\"\"自定义异常类\"\"\"\n",
    "    pass\n",
    "\n",
    "def check_positive(number):\n",
    "    if number < 0:\n",
    "        raise NegativeNumberError(\"数字不能为负数！\")\n",
    "    return number\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81767355-4ff7-4afc-bf71-43490b119f0d",
   "metadata": {},
   "source": [
    "1. 在这个示例中，当 `number` 为负数时，程序会引发 `NegativeNumberError` 异常，并输出自定义的错误信息。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec9b521169e87875",
   "metadata": {},
   "source": [
    "### 8. 列表、元组、字典与集合\n",
    "\n",
    "#### 讲解：\n",
    "\n",
    "Python中的基本数据结构包括列表、元组、字典和集合。列表是可变的有序集合，元组是不可变的有序集合，字典是键值对集合，而集合是无序且不重复的元素\n",
    "\n",
    "集合。理解这些数据结构的特性和用法对于数据处理非常重要。\n",
    "\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d543e49cd7c15804",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:15:30.982608Z",
     "start_time": "2024-09-01T17:15:30.974146Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "水果列表: ['apple', 'banana', 'cherry', 'orange']\n",
      "第一个水果: apple\n",
      "水果数量: 4\n",
      "平方列表: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n",
      "坐标: (10.0, 20.0)\n",
      "个人信息字典: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': 'alice@example.com'}\n",
      "姓名: Alice\n",
      "name: Alice\n",
      "age: 25\n",
      "city: New York\n",
      "email: alice@example.com\n",
      "颜色集合: {'yellow', 'blue', 'red', 'green'}\n",
      "交集: {3, 4}\n",
      "并集: {1, 2, 3, 4, 5, 6}\n",
      "差集: {1, 2}\n"
     ]
    }
   ],
   "source": [
    "# 列表示例\n",
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "fruits.append(\"orange\")  # 添加元素\n",
    "print(\"水果列表:\", fruits)\n",
    "print(\"第一个水果:\", fruits[0])\n",
    "print(\"水果数量:\", len(fruits))\n",
    "\n",
    "# 列表推导式\n",
    "squares = [x ** 2 for x in range(10)]\n",
    "print(\"平方列表:\", squares)\n",
    "\n",
    "# 元组示例\n",
    "coordinates = (10.0, 20.0)\n",
    "print(\"坐标:\", coordinates)\n",
    "\n",
    "# 字典示例\n",
    "person = {\"name\": \"Alice\", \"age\": 25, \"city\": \"New York\"}\n",
    "person[\"email\"] = \"alice@example.com\"  # 添加键值对\n",
    "print(\"个人信息字典:\", person)\n",
    "print(\"姓名:\", person[\"name\"])\n",
    "\n",
    "# 字典的遍历\n",
    "for key, value in person.items():\n",
    "    print(f\"{key}: {value}\")\n",
    "\n",
    "# 集合示例\n",
    "colors = {\"red\", \"green\", \"blue\"}\n",
    "colors.add(\"yellow\")  # 添加元素\n",
    "print(\"颜色集合:\", colors)\n",
    "\n",
    "# 集合运算\n",
    "set_a = {1, 2, 3, 4}\n",
    "set_b = {3, 4, 5, 6}\n",
    "print(\"交集:\", set_a & set_b)\n",
    "print(\"并集:\", set_a | set_b)\n",
    "print(\"差集:\", set_a - set_b)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "531c113c-9461-4f4b-a436-4a66135ba8fb",
   "metadata": {},
   "source": [
    "### 9. 文件的读写\n",
    "\n",
    "#### 讲解：\n",
    "\n",
    "在编程中，文件的读写操作是非常常见的需求。Python 提供了简单而强大的文件读写功能，通过内置的 `open()` 函数，我们可以轻松地对文件进行读取和写入操作。\n",
    "\n",
    "文件的读写模式主要包括：\n",
    "\n",
    "- **`'r'`**：读取模式（默认模式）。打开文件以读取数据，文件必须存在，否则会抛出 `FileNotFoundError` 异常。\n",
    "- **`'w'`**：写入模式。如果文件不存在，会创建新文件；如果文件存在，会清空文件内容。\n",
    "- **`'a'`**：追加模式。将数据写入文件的末尾，如果文件不存在，会创建新文件。\n",
    "- **`'b'`**：二进制模式。用于处理非文本文件（如图片、音频），通常与其他模式组合使用，如 `'rb'`、`'wb'`。\n",
    "- **`'+'`**：读写模式。允许同时读写文件，通常与其他模式组合使用，如 `'r+'`、`'w+'`。\n",
    "\n",
    "文件操作通常包括以下步骤：\n",
    "\n",
    "1. 使用 `open()` 函数打开文件，获得文件对象。\n",
    "2. 通过文件对象进行读写操作。\n",
    "3. 完成操作后，使用 `close()` 方法关闭文件，以释放资源。\n",
    "\n",
    "Python 还支持使用 `with` 语句来打开文件，这样在块结束后，文件会自动关闭，确保资源及时释放。\n",
    "\n",
    "#### 代码示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "af0da220-4560-4e62-9cb1-4ef7bafceba0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件内容:\n",
      " 这是第一行文本。\n",
      "这是第二行文本。\n",
      "\n",
      "读取到的行: 这是第一行文本。\n",
      "读取到的行: 这是第二行文本。\n",
      "更新后的文件内容:\n",
      " 这是第一行文本。\n",
      "这是第二行文本。\n",
      "这是追加的一行文本。\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 写入文件示例\n",
    "with open('example.txt', 'w') as file:\n",
    "    file.write(\"这是第一行文本。\\n\")\n",
    "    file.write(\"这是第二行文本。\\n\")\n",
    "\n",
    "# 读取文件示例\n",
    "with open('example.txt', 'r') as file:\n",
    "    content = file.read()\n",
    "    print(\"文件内容:\\n\", content)\n",
    "\n",
    "# 逐行读取文件示例\n",
    "with open('example.txt', 'r') as file:\n",
    "    for line in file:\n",
    "        print(\"读取到的行:\", line.strip())\n",
    "\n",
    "# 追加写入文件示例\n",
    "with open('example.txt', 'a') as file:\n",
    "    file.write(\"这是追加的一行文本。\\n\")\n",
    "\n",
    "# 读取文件内容示例\n",
    "with open('example.txt', 'r') as file:\n",
    "    print(\"更新后的文件内容:\\n\", file.read())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "547f2490-981c-4685-9a31-30403e85a8bb",
   "metadata": {},
   "source": [
    "**代码讲解：**\n",
    "\n",
    "1. **写入文件**：\n",
    "   - `with open('example.txt', 'w') as file:` 打开一个名为 `example.txt` 的文件，使用写入模式 `'w'`。如果文件不存在，将创建一个新文件；如果文件已存在，内容将被清空。\n",
    "   - `file.write(\"这是第一行文本。\\n\")` 将文本写入文件，`\\n` 表示换行符。`with` 语句块结束时，文件将自动关闭。\n",
    "\n",
    "2. **读取文件**：\n",
    "   - `with open('example.txt', 'r') as file:` 打开文件以读取内容。`file.read()` 读取文件的全部内容，并将其存储在 `content` 变量中。\n",
    "   - `print(content)` 输出读取的内容。\n",
    "\n",
    "3. **逐行读取文件**：\n",
    "   - 通过 `for line in file:` 循环逐行读取文件内容。`line.strip()` 用于去除行末的换行符。\n",
    "\n",
    "4. **追加写入文件**：\n",
    "   - `with open('example.txt', 'a') as file:` 以追加模式 `'a'` 打开文件，将新内容写入文件的末尾，而不会覆盖已有内容。\n",
    "\n",
    "5. **读取更新后的文件内容**：\n",
    "   - 再次读取文件内容，验证追加操作是否成功。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef11a32b-2135-4145-84b5-cb8f6a937066",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
